﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Elasticsearch.Synchronize.Common.Enum;
using Elasticsearch.Synchronize.Common.UUID;
using Elasticsearch.Synchronize.Domain.Aggregates.SynchronizeAggregate;
using Elasticsearch.Synchronize.Domain.Events;
using Elasticsearch.Synchronize.Domain.Interface;

namespace Elasticsearch.Synchronize.DomainEventHandler.Handler
{
    public class AddRuleItemEventHandler : MediatR.NotificationHandler<AddRuleItemDomainEvent>
    {
        private readonly IdGenerator _idGenerator;

        private readonly ISynchronizeItemRepository _repository;

        public AddRuleItemEventHandler(IdGenerator idGenerator, ISynchronizeItemRepository repository)
        {
            _idGenerator = idGenerator;
            _repository = repository;
        }

        protected override void HandleCore(AddRuleItemDomainEvent notification)
        {
            var rule = notification.SynchronizeRule;

            SynchronizeItem synchronizeItem = new SynchronizeItem
            {
                RuleId = rule.Identity,
                Identity = _idGenerator.Get(),
                MongoSeverUrl = rule.RuleItemMongoServerUrl,
                MongoDatabase = rule.RuleItemMongoDatabase,
                MongoCollection = rule.RuleItemMongoCollection,
                JsonFilter = rule.CurrentRuleItemFilter,
                ElasticsearchServerUrl = rule.RuleItemElasticsearchServerUrl,
                ElasticsearchIndexName = rule.RuleItemElasticsearchIndexName,
                ElasticsearchTypeName = rule.RuleItemElasticsearchTypeName,
                Threshold = 10000,
                Enabled = true,
                State = SyncState.Idle
            };

            _repository.Add(synchronizeItem);
        }
    }
}